<template>
  <div>
    <el-form :model="formData" inline ref="formData" :rules="formRules" label-position="top" class="row-form"
             v-if="formData">
      <el-card class="box-card">
        <div class="card-view">

          <div class="card-title">基础信息</div>

          <el-form-item label="所属园区" prop="housingAssess.gardenHomeId" class="form-item-css">
            <el-select v-model="formData.housingAssess.gardenHomeId" filterable remote reserve-keyword
                       placeholder="请输入园区关键词"
                       :remote-method="remoteMethod" style="width: 100%" :disabled="isDisabled">
              <el-option v-for="(item, index) in selectOptions" :key="index" :label="item.gardenName"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="楼号" prop="housingAssess.building" class="form-item-css">
            <el-input type="number" v-model="formData.housingAssess.building" :disabled="isDisabled"
                      placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="单元号" prop="housingAssess.unit" class="form-item-css">
            <el-input type="number" v-model="formData.housingAssess.unit" :disabled="isDisabled"
                      placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="房号" prop="housingAssess.room" class="form-item-css">
            <el-input type="number" v-model="formData.housingAssess.room" :disabled="isDisabled"
                      placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="房屋面积" prop="housingAssess.houseArea" class="form-item-css">
            <el-input type="number" v-model="formData.housingAssess.houseArea" :disabled="isDisabled"
                      placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="房屋类型" class="form-item-css" prop="housingAssess.houseType">
            <el-select v-model="formData.housingAssess.houseType" :disabled="isDisabled" style="width: 100%"
                       placeholder="请选择">
              <el-option label="写字楼" :value="1"/>
              <el-option label="商铺" :value="2"/>
              <el-option label="土地" :value="3"/>
            </el-select>
          </el-form-item>
          <el-form-item label="朝向" prop="housingAssess.orientation" class="form-item-css">
            <el-select v-model="formData.housingAssess.orientation" :disabled="isDisabled" style="width: 100%"
                       placeholder="请选择">
              <el-option label="东" value="东"/>
              <el-option label="南" value="南"/>
              <el-option label="西" value="西"/>
              <el-option label="北" value="北"/>
              <el-option label="东南" value="东南"/>
              <el-option label="西南" value="西南"/>
              <el-option label="东北" value="东北"/>
              <el-option label="西北" value="西北"/>
              <el-option label="东西" value="东西"/>
            </el-select>
          </el-form-item>
          <el-form-item label="层高" prop="housingAssess.storeyHeight" class="form-item-css">
            <el-input type="number" v-model="formData.housingAssess.storeyHeight" :disabled="isDisabled"
                      placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="房产格局" prop="housingAssess.pattern" class="form-item-css">
            <el-input v-model="formData.housingAssess.pattern" :disabled="isDisabled" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="地址" class="form-item-css" prop="housingAssess.provinces">
            <el-cascader v-model="formData.housingAssess.provinces" ref="cascader" style="width: 100%"
                         :props="props" @change="handleChange" :key="formData.housingAssess.provinceCityCountyId"
                         placeholder="请选择" :disabled="isDisabled"/>
          </el-form-item>
          <el-form-item label="详情地址" prop="housingAssess.address" class="form-item-css">
            <el-input v-model="formData.housingAssess.address" :disabled="isDisabled" placeholder="请输入"></el-input>
          </el-form-item>

          <div class="form-item-css"></div>
          <el-form-item label="房产证" prop="" style="width: 100%;">
            <div class="row-start">
              <div class="image-list" v-for="(item, index) in formData.housingAssessImage">
                <el-image :src="item.image" fit="cover" class="image-item"></el-image>
                <div class="row-div image-hover" v-if="detailState != 3 && !isDisabled">
                  <i class="el-icon-delete" @click="imageListDelete(item, index)"></i>
                </div>
              </div>
              <UploadFile :file-list="formData.housingAssessImage" listType @change="fileListChange"
                          v-if="detailState != 3 && !isDisabled"/>
            </div>
          </el-form-item>
        </div>
      </el-card>

      <el-card class="box-card">
        <div class="card-view">
          <div class="card-title">房东信息</div>
          <el-form-item label="房东姓名" prop="housingMaster.name" class="form-item-css">
            <el-input v-model="formData.housingMaster.name" :disabled="isDisabled" v-if="detailState == 3"/>
            <el-select v-model="formData.housingAssess.housingMasterId" filterable remote reserve-keyword
                       placeholder="请输入房东姓名关键词"
                       :remote-method="getLandlordList" style="width: 100%" :disabled="isDisabled" v-else
                       @change="selectChange($event, 'housingMaster')">
              <el-option v-for="(item, index) in landlordList" :key="index" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房东手机号" prop="housingMaster.phone" class="form-item-css">
            <el-input v-model="formData.housingMaster.phone" placeholder="请选择" :disabled="isDisabled"/>
          </el-form-item>
          <div class="form-item-css"></div>
          <el-form-item label="房东身份证国徽面" class="form-item-css">
            <div class="row-start" style="flex-wrap: wrap; width: 100%;">
              <el-image :src="formData.housingMaster.cardPhotoJust" fit="cover" class="start-image"
                        style="width: 100%"></el-image>
            </div>
          </el-form-item>
          <el-form-item label="房东身份证人像面" class="form-item-css">
            <div class="row-start" style="flex-wrap: wrap; width: 100%;">
              <el-image :src="formData.housingMaster.cardPhotoBack" fit="cover" class="start-image"
                        style="width: 100%"></el-image>
            </div>
          </el-form-item>
        </div>
      </el-card>

      <el-card class="box-card" v-if="formData.houseAgent">
        <div class="card-view">
          <div class="card-title">关联经纪人</div>
          <el-form-item label="经纪人UID" prop="houseAgent.id" class="form-item-css" v-if="detailState == 3">
            <el-input v-model="formData.houseAgent.id" :disabled="isDisabled"/>
          </el-form-item>
          <el-form-item label="经纪人姓名" prop="housingAssess.houseAgentId" class="form-item-css">
            <el-input v-model="formData.houseAgent.name" :disabled="isDisabled" v-if="detailState == 3"/>
            <el-select v-model="formData.housingAssess.houseAgentId" filterable remote reserve-keyword
                       placeholder="请输入经纪人姓名关键词"
                       :remote-method="getBrokerList" style="width: 100%" :disabled="isDisabled" v-else
                       @change="selectChange($event, 'houseAgent')">
              <el-option v-for="(item, index) in brokerList" :key="index" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="经纪人手机号" prop="houseAgent.phone" class="form-item-css">
            <el-input v-model="formData.houseAgent.phone" placeholder="请选择" :disabled="isDisabled"/>
          </el-form-item>
        </div>
      </el-card>
      <div class="row-div" style="margin: 30px 0" v-if="detailState == 1">
        <el-button style="width: 300px" @click="$router.push('/housingManage/houseOwner')">取 消</el-button>
        <el-button type="primary" style="width: 300px" @click="onSubmit(1)">提 交</el-button>
      </div>
      <div class="row-div" style="margin: 30px 0" v-if="detailState == 2">
        <el-button style="width: 300px" @click="$router.push('/housingManage/houseOwner')">取 消</el-button>
        <el-button type="primary" style="width: 300px" @click="onSubmit(2)">保 存</el-button>
      </div>
      <div class="row-div" style="margin: 30px 0" v-else-if="detailState == 3">
        <el-button style="width: 300px" @click="onReject">驳 回</el-button>
        <el-button type="primary" style="width: 300px" @click="onSubmit(3)">通 过</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import {getProvinces} from '@/utils/common.js'
  export default {
    computed: {
      ...mapGetters(['confirm'])
    },
    name: 'housingDetail',
    data() {
      return {
        detailId: null,
        detailState: null,
        isDisabled: false,
        formData: {
          gardenName: null,
          houseAgent: {
            id: null,
            name: null,
            phone: null
          },
          housingAssess: {
            id: null,
            provinces: null, // 省市区
            province: null,
            city: null,
            county: null,
            address: null,
            houseArea: null,
            houseType: null,
            orientation: null,
            pattern: null,
            roomNumber: null,
            building: null,
            unit: null,
            room: null,
            storeyHeight: null,
            gardenHomeId: null, // 园区ID
            houseAgentId: null, // 经纪人ID
            housingMasterId: null // 房东ID
          },
          housingAssessImage: [],
          housingMaster: {
            cardPhotoBack: null,
            cardPhotoJust: null,
            name: null,
            phone: null
          }
        },
        formRules: {
          'housingAssess.gardenHomeId': [
            { required: true, message: '请选择园区', trigger: 'change' }
          ],
          'housingAssess.building': [
            { required: true, message: '请输入楼号', trigger: 'blur' }
          ],
          'housingAssess.unit': [
            { required: true, message: '请输入单元号', trigger: 'blur' }
          ],
          'housingAssess.room': [
            { required: true, message: '请输入房号', trigger: 'blur' }
          ],
          'housingAssess.houseArea': [
            { required: true, message: '请输入房屋面积', trigger: 'blur' }
          ],
          'housingAssess.houseType': [
            { required: true, message: '请选择房屋类型', trigger: 'change' }
          ],
          'housingAssess.orientation': [
            { required: true, message: '请输入朝向', trigger: 'blur' }
          ],
          'housingAssess.storeyHeight': [
            { required: true, message: '请输入层高', trigger: 'blur' }
          ],
          'housingAssess.pattern': [
            { required: true, message: '请输入房产格局', trigger: 'blur' }
          ],
          'housingAssess.provinces': [
            { required: true, message: '请选择地址', trigger: 'change' }
          ],
          'housingAssess.address': [
            { required: true, message: '请输入详情地址', trigger: 'blur' }
          ],

          'housingMaster.name': [
            { required: true, message: '请选择房东姓名', trigger: 'change' }
          ],

          'housingMaster.phone': [
            { required: true, message: '请选择房东手机号', trigger: 'change' }
          ],

          'houseAgent.name': [
            { required: true, message: '请选择经纪人', trigger: 'change' }
          ],
          'housingAssess.houseAgentId': [
            { required: true, message: '请选择经纪人', trigger: 'change' }
          ],

          'houseAgent.phone': [
            { required: true, message: '请选择经纪人手机号', trigger: 'change' }
          ]

        },
        props: getProvinces(),
        selectOptions: [],
        landlordList: [],
        brokerList: [],
        gardenName: null

      }
    },
    beforeMount() {
      this.detailState = this.$route.query.type || null
      if (this.$route.query.id) {
        this.isDisabled = !(!((this.detailState === '3' || '7') && this.$route.query.id))
        this.detailId = this.$route.query.id
        this.getInfoRequest()
      }
    },
    methods: {
      /**
       * 远程搜索select变化事件
       */
      selectChange(event, key) {
        if (key == 'housingMaster') {
          const entity = this.landlordList.find(item => item.id == event)
          this.formData.housingMaster = entity
        }
        if (key == 'houseAgent') {
          const entity = this.brokerList.find(item => item.id == event)
          this.formData.houseAgent = entity
        }
      },
      /**
       * 内容图片变化事件
       */
      async fileListChange(event) {
        if (this.detailId && this.detailState == 2) {
          const imageArr = JSON.parse(JSON.stringify(event))
          const entity = imageArr.pop()
          const res = await this.$ajax.post('/huosing/image/add', {
            'housingAssessId': this.formData.housingAssess.id,
            'image': entity
          })
          return this.formData.housingAssessImage.push(res.data)
        }
        this.formData.housingAssessImage.push({ image: event.pop() })
      },
      /**
       * 图片列表删除事件
       */
      async imageListDelete(item, index) {
        if (this.detailId && this.detailState == 2) {
          await this.$ajax.get(`/huosing/image/remove?id=${item.id}`)
        }
        this.formData.housingAssessImage.splice(index, 1)
      },
      /**
       *  园区列表
       */
      async remoteMethod(str, query = null) {
        const res = await this.$ajax.get(`/garden/list?gardenName=${str?.trim() || ''}${query || ''}`)
        this.selectOptions = res.rows
      },
      /**
       *  房东列表
       */
      async getLandlordList(str, type = 0) {
        const keyArr = ['name', 'phone']
        const res = await this.$ajax.get(`/my/house/master/list?${keyArr[type]}=${str}`)
        this.landlordList = res.rows
      },
      /**
       *  经纪人列表
       */
      async getBrokerList(str, type = 0) {
        const keyArr = ['name', 'phone']
        const res = await this.$ajax.get(`/my/house/agent/list?${keyArr[type]}=${str}`)
        this.brokerList = res.rows
      },
      /**
       * 省市区变化事件
       */
      handleChange(row) {
        const entity = this.$refs.cascader.getCheckedNodes()[0]
        const list = entity && entity.pathLabels && entity.pathLabels.length > 0 ? entity.pathLabels : [null, null, null]
        let arr = ['province', 'city', 'county']
        for (let i = 0; i < list.length; i++) this.formData.housingAssess[arr[i]] = list[i]
      },
      /**
       * 驳回事件
       */
      onReject() {
        this.$prompt('请输入驳回理由', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'textarea'
        }).then(async({ value }) => {
          await this.$ajax.post('/my/house/assess/update', { id: this.detailId, checkStatus: 2, checkReason: value })
          this.$message.success('操作成功!')
          this.getInfoRequest()
        })
      },

      /**
       * 通过事件
       */
      async onSubmit(type) {
        if (type == 1 || type == 2) {
          this.$refs.formData.validate(async(valid) => {
            if (!valid) return
            const formData = JSON.parse(JSON.stringify(this.formData))
            formData.housingAssess.provinceCityCountyId = formData.housingAssess.provinces.join(',')
            formData.housingAssess.roomNumber = [formData.housingAssess.building, formData.housingAssess.unit, formData.housingAssess.room].join(',')
            await this.$ajax.post(type == 2 ? '/my/house/assess/backstage/update' : '/my/house/assess/backstage/add', formData)
            this.$message.success('操作成功!')
            this.$router.push('/housingManage/houseOwner')
          })
        }
        if (type == 3) {
          this.$confirm('确认通过审核吗?', '提示', this.confirm.options).then(async() => {
            await this.$ajax.post('/my/house/assess/update', { id: this.detailId, checkStatus: 1 })
            this.$message.success('操作成功!')
            this.$router.push('/housingManage/houseOwner')
          })
        }
      },
      async getInfoRequest() {
        const res = await this.$ajax.get(`/my/house/assess/backstage/info?id=${this.detailId}`)
        if (res.data.housingAssess?.roomNumber) {
          const arr = ['building', 'unit', 'room']
          const strArr = res.data.housingAssess.roomNumber.split(',')
          arr.forEach((item, index) => res.data.housingAssess[item] = strArr[index] || null)
        }
        if (res.data.housingAssess?.provinceCityCountyId) {
          res.data.housingAssess.provinces = res.data.housingAssess.provinceCityCountyId.split(',')
        }
        this.remoteMethod(res.data.gardenName || '')
        if (res.data.housingMaster?.name) {
          this.getLandlordList(res.data.housingMaster.name)
        }
        if (res.data.houseAgent?.name) {
          this.getBrokerList(res.data.houseAgent.name)
        }
        this.formData = res.data
      }
    }
  }
</script>

<style scoped lang="scss">
  .box-card + .box-card {
    margin-top: 20px;
  }

  .image-list {
    width: 148px;
    height: 148px;
    position: relative;
    margin-right: 10px;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    &:hover > .image-hover {
      display: flex;
      z-index: 1;
    }
    .image-item, .image-hover {
      width: 100%;
      height: 100%;
      border-radius: 6px;
    }
    .image-hover {
      position: absolute;
      top: 0;
      left: 0;
      display: none;
      background: rgba(0, 0, 0, 0.5);
      color: white;
      font-size: 20px;
    }
  }

  .card-view {
    width: 100%;
    .card-title {
      width: 200px;
      font-weight: bold;
      font-size: 18px;
      padding-bottom: 10px;
      margin-bottom: 20px;
      position: relative;
      &:before {
        content: "";
        width: 200px;
        height: 1px;
        background: #000000;
        position: absolute;
        bottom: 0;
        left: 0;
      }
    }

    .form-item-css {
      width: calc(100% / 3 - 10px);
      position: relative;
      .delete-but {
        position: absolute;
        color: red;
        z-index: 2;
        right: 0;
        top: -40px;
      }
    }
  }

  .start-image {
    width: 178px;
    height: 178px;
  }

  .start-image + .start-image {
    margin-left: 15px;
  }

  .image-view {
    width: 100%;
    height: 178px;
    position: relative;
    .el-icon-circle-close {
      font-size: 30px;
      color: red;
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 100;
    }
    .el-icon-circle-close:hover {
      cursor: pointer;
    }
  }
</style>
